package org.lmj.dim.config;

import lombok.Data;
import lombok.ToString;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

/**
 * Created by lmj on 2021/3/13.
 */
@Data
@ToString
public class SessionUser implements UserDetails {
    /**
     * 对接spring-security的权限类：（必须要符合security的规范）---如何写一个框架：采用aop思想+面向接口编程
     * 此类必须有三个属性
     * 用户名，密码，权限列表
     */
    private Integer id;
    private String username;
    private String password;
    private String avatar;
    //权限
    private Collection<? extends GrantedAuthority> authorities;

    SessionUser(String username, String password, List<GrantedAuthority> authorities){
        this.username = username;
        this.password = password;
        this.authorities = authorities ;
    }
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    // 账户是否未过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    // 账户是否未锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    // 密码是否未过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    // 账户是否激活
    @Override
    public boolean isEnabled() {
        return true;
    }

    //获得当前登陆用户对应的对象。
    public static SessionUser getCurUser(){
        SecurityContext context = SecurityContextHolder.getContext();
        System.out.println(context);
        Object principal = SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        if (principal instanceof SessionUser){
            SessionUser userDetails = (SessionUser)principal;
            System.out.println("当前用户:"+userDetails);
            return userDetails;
        }
        return null;
    }
}